package com.sti.framework.models.User.controller;

import com.sti.framework.core.annotation.authorization.Authorization;
import com.sti.framework.core.security.jwt.JwtUtil;
import com.sti.framework.core.web.Page;
import com.sti.framework.core.web.ResponseBodyEntity;
import com.sti.framework.core.web.SimplePage;
import com.sti.framework.models.User.data.RoleAuthority;
import com.sti.framework.models.User.service.RoleAuthorityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;

@RestController
@RequestMapping("/Api/RoleAuthority")
@Api(tags = "角色管理", value = "用户管理")
public class RoleAuthorityController {

    @Inject
    private RoleAuthorityService roleAuthorityService;

    @ApiOperation(value = "权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "登陆后获取的签名", paramType = "header", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name="role_id", value="角色id", required=true, paramType="query", dataTypeClass = Long.class, example = "1")
    })
    @GetMapping("/List")
    public ResponseBodyEntity<SimplePage<RoleAuthority>> List(HttpServletRequest request, Page page, @Valid Long role_id) {
        JwtUtil.checkJWT(request.getHeader("token"));
        if (role_id == null){
            return ResponseBodyEntity.fail(ResponseBodyEntity.ResponseStatus.FAIL, "缺少参数role_id");
        }
        return ResponseBodyEntity.success(roleAuthorityService.getAll(page, role_id));
    }

    @ApiOperation(value = "修改权限", hidden = true)
    @ApiImplicitParam(name = "token", value = "登陆后获取的签名", paramType = "header", dataTypeClass = String.class, required = true)
    @Authorization(tag = "/Modify", describes = "修改权限")
    @PostMapping(value = "/Modify")
    public ResponseBodyEntity Modify(@RequestBody @Valid ArrayList<RoleAuthority> roleAuthority) {

        if (roleAuthority.isEmpty()){
            return ResponseBodyEntity.fail(ResponseBodyEntity.ResponseStatus.USER_ERROR_21410);
        }

        // 删除所有权限
        roleAuthorityService.deleteForRole(roleAuthority.get(0).getRole_id());

        // 增加新权限
        roleAuthorityService.saveBatch(roleAuthority);
        return ResponseBodyEntity.success();
    }
}
